// 文件系统相关的类型定义

export interface FileItem {
  name: string;
  path: string;
  is_directory: boolean;
  size?: number;
  modified?: number;
  extension?: string;
  language?: string;
}

export interface WorkspaceInfo {
  path: string;
  name: string;
  files: FileItem[];
}

export interface FileOperationResult {
  success: boolean;
  message: string;
  path?: string;
}

export interface FileTreeNode extends FileItem {
  children?: FileTreeNode[];
  expanded?: boolean;
  selected?: boolean;
  level: number;
  parent?: FileTreeNode;
}

export interface FileSystemState {
  currentWorkspace?: WorkspaceInfo;
  selectedFiles: string[];
  expandedDirectories: Set<string>;
  searchQuery: string;
  filteredFiles: FileTreeNode[];
  fileTree: FileTreeNode[];
}

export interface FileOperation {
  type: 'create' | 'delete' | 'rename' | 'move';
  path: string;
  newPath?: string;
  isDirectory: boolean;
  timestamp: number;
}

export interface FileOperationHistory {
  operations: FileOperation[];
  currentIndex: number;
}

// 文件状态枚举
export enum FileStatus {
  Normal = 'normal',
  Modified = 'modified',
  Added = 'added',
  Deleted = 'deleted',
  Conflicted = 'conflicted',
}

// 文件图标映射
export interface FileIconMapping {
  [key: string]: string;
}

// 语言到图标的映射
export const LANGUAGE_ICONS: FileIconMapping = {
  typescript: 'typescript',
  javascript: 'javascript',
  python: 'python',
  rust: 'rust',
  java: 'java',
  cpp: 'cpp',
  c: 'c',
  go: 'go',
  html: 'html',
  css: 'css',
  json: 'json',
  markdown: 'markdown',
  xml: 'xml',
  yaml: 'yaml',
  toml: 'toml',
  shell: 'shell',
  sql: 'sql',
  text: 'file-text',
};

// 文件夹图标
export const FOLDER_ICONS = {
  default: 'folder',
  open: 'folder-open',
  src: 'folder-code',
  test: 'folder-check',
  docs: 'folder-book',
  config: 'folder-cog',
  assets: 'folder-image',
  node_modules: 'folder-x',
  '.git': 'folder-git',
  '.vscode': 'folder-code',
  'target': 'folder-output',
  'dist': 'folder-output',
  'build': 'folder-output',
};

// 特殊文件名图标映射
export const SPECIAL_FILE_ICONS: FileIconMapping = {
  'package.json': 'package',
  'package-lock.json': 'package',
  'yarn.lock': 'package',
  'pnpm-lock.yaml': 'package',
  'Cargo.toml': 'package',
  'Cargo.lock': 'package',
  'README.md': 'book-open',
  'LICENSE': 'file-text',
  'Dockerfile': 'container',
  '.gitignore': 'git-branch',
  '.gitattributes': 'git-branch',
  'tsconfig.json': 'settings',
  'vite.config.ts': 'settings',
  'tailwind.config.js': 'settings',
  '.env': 'key',
  '.env.local': 'key',
  '.env.development': 'key',
  '.env.production': 'key',
};

// 获取文件图标
export function getFileIcon(file: FileItem): string {
  // 检查特殊文件名
  if (SPECIAL_FILE_ICONS[file.name]) {
    return SPECIAL_FILE_ICONS[file.name];
  }

  // 如果是目录
  if (file.is_directory) {
    return FOLDER_ICONS[file.name as keyof typeof FOLDER_ICONS] || FOLDER_ICONS.default;
  }

  // 根据语言获取图标
  if (file.language && LANGUAGE_ICONS[file.language]) {
    return LANGUAGE_ICONS[file.language];
  }

  // 默认文件图标
  return LANGUAGE_ICONS.text;
}

// 获取文件夹图标（考虑展开状态）
export function getFolderIcon(file: FileItem, isExpanded: boolean): string {
  if (!file.is_directory) {
    return getFileIcon(file);
  }

  const specialIcon = FOLDER_ICONS[file.name as keyof typeof FOLDER_ICONS];
  if (specialIcon && specialIcon !== FOLDER_ICONS.default) {
    return specialIcon;
  }

  return isExpanded ? FOLDER_ICONS.open : FOLDER_ICONS.default;
}

// 格式化文件大小
export function formatFileSize(bytes?: number): string {
  if (!bytes) return '';
  
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = bytes;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  return `${size.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`;
}

// 格式化修改时间
export function formatModifiedTime(timestamp?: number): string {
  if (!timestamp) return '';
  
  const date = new Date(timestamp * 1000);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 小于1分钟
  if (diff < 60000) {
    return 'Just now';
  }
  
  // 小于1小时
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000);
    return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
  }
  
  // 小于1天
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000);
    return `${hours} hour${hours > 1 ? 's' : ''} ago`;
  }
  
  // 小于1周
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000);
    return `${days} day${days > 1 ? 's' : ''} ago`;
  }
  
  // 显示具体日期
  return date.toLocaleDateString();
}

// 检查文件是否匹配搜索查询
export function matchesSearchQuery(file: FileItem, query: string): boolean {
  if (!query.trim()) return true;
  
  const searchTerm = query.toLowerCase();
  return !!(file.name.toLowerCase().includes(searchTerm) ||
         (file.extension && file.extension.toLowerCase().includes(searchTerm)) ||
         (file.language && file.language.toLowerCase().includes(searchTerm)));
}

// 构建文件树结构
export function buildFileTree(files: FileItem[], basePath: string): FileTreeNode[] {
  const tree: FileTreeNode[] = [];
  const nodeMap = new Map<string, FileTreeNode>();
  
  // 首先创建所有节点
  files.forEach(file => {
    const node: FileTreeNode = {
      ...file,
      children: file.is_directory ? [] : undefined,
      expanded: false,
      selected: false,
      level: 0,
    };
    nodeMap.set(file.path, node);
  });
  
  // 构建树结构
  files.forEach(file => {
    const node = nodeMap.get(file.path)!;
    const parentPath = file.path.substring(0, file.path.lastIndexOf('/'));
    
    if (parentPath === basePath || parentPath === '') {
      // 根级别文件
      tree.push(node);
    } else {
      // 子文件，找到父节点
      const parent = nodeMap.get(parentPath);
      if (parent && parent.children) {
        node.parent = parent;
        node.level = parent.level + 1;
        parent.children.push(node);
      }
    }
  });
  
  return tree;
}
